package com.halden.mycache.support.saveStrategy.RDBSaveStrategy.impl;

import com.halden.mycache.support.saveStrategy.RDBSaveStrategy.IRDBSaveMode;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author: halden
 * @Data:2023/2/8 10:44
 * @Description:
 */
public abstract class RdbAbstractSaveMode<K,V> implements IRDBSaveMode<K,V> {

    /**
     * 默认字符集为UTF8
     */
    private static final String charset = "UTF-8";

    /**
     * 将持久化字符串写入文件
     * @param string
     * @param fileName
     * @since 0.0.3
     */
    public void saveString(String string, String fileName) {
        try {
            File file = new File(fileName);
            File parentFile = file.getParentFile();
            //如果json文件已经存在，则删除
            file.deleteOnExit();
            //如果目录不存在，则创建
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            FileChannel channel = randomAccessFile.getChannel();
            //写入文件
            channel.write(ByteBuffer.wrap(string.getBytes(charset)));
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 从文件读取持久化字符串
     * @param file
     * @return
     * @since 0.0.3
     */
    public String readString(File file){
        String result = null;
        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
            FileChannel fileChannel = randomAccessFile.getChannel();
            StringBuffer stringBuffer = new StringBuffer();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int byteNum = fileChannel.read(buffer);
            while(byteNum != -1){
                // 读写切换（内部游标操作）
                buffer.flip();
                // buffer中是否有内容
                while (buffer.hasRemaining()){
                    char c = (char) buffer.get();
                    stringBuffer.append(c);
                }
                // 清空缓冲区
                buffer.clear();
                byteNum = fileChannel.read(buffer);
            }
            result = stringBuffer.toString();
        } catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
}
